<template>
	<view class="Visitor">
		<view v-if="hasCustomer" class="hasCustomer">
			<view class="imgBox">
				<view style="width: 100%; font-size: 30rpx; text-align: center; background-color: rgba(0,0,0,.3);position: absolute;top: 0;left: 0;z-index: 9999;color: #FFFFFF;">
					点击图片更换
				</view>
				<avatar selWidth="540upx" selHeight="720upx" expWidth="420upx" expHeight="560upx" @upload="myUpload" :quality='.8'
				 bgImg='rgba(0,0,0,0)' :avatarSrc="url" avatarStyle="width: 250upx; height: 333.33upx;border-radius:0%;">
				</avatar>
			</view>
			<view class="Form_vis">
				<u-form :model="form" ref="uForm">
					<u-form-item　left-icon='account' :border-bottom='false' label="访客姓名" :label-width="170">
						<u-input v-model="form.VisitorName" />
					</u-form-item>
					<u-form-item　left-icon='phone-fill' :border-bottom='false' label="　手机号" :label-width="170">
						<u-input v-model="form.Phone" />
					</u-form-item>
					<u-form-item　left-icon='coupon' :border-bottom='false' label="　证件号" :label-width="170">
						<u-input v-model="form.VisitorCardNo" />
					</u-form-item>
					<u-form-item　left-icon='man-add' :border-bottom='false' label="　被访人" :label-width="170">
						<u-input v-model="form.Interviewee" />
					</u-form-item>
					<u-form-item　left-icon='chat' :border-bottom='false' label="　事　由" :label-width="170">
						<u-input v-model="form.Reason" type="select" @click="ReasonShow = true" />
						<u-action-sheet :list="Reasonlist" v-model="ReasonShow" @click="actionSheetCallback"></u-action-sheet>
					</u-form-item>
					<u-form-item　left-icon='order' :border-bottom='false' label="　备　注" :label-width="170">
						<u-input v-model="form.Remark" />
					</u-form-item>
					<u-form-item　left-icon='calendar' :border-bottom='false' label="　有效期" :label-width="170">
						<u-input v-model="form.Expiry" @click='pickerShow = true' type="select" />
						<u-picker mode="time" v-model="pickerShow" :default-time="form.Expiry" :params="params" @confirm='setTime'></u-picker>
					</u-form-item>
					<u-form-item　left-icon='lock' :border-bottom='false' label="　权限组" :label-width="170">
						<!-- <u-input v-model="Accesstext" @click='Accessshow = true' type="select" /> -->
						<!-- <u-select v-model="Accessshow" :mask-close-able='false' :list="AccessGroup" @confirm.stop='AccessClick'></u-select> -->
						<picker style="width: 100%;height: 100%;" class="uni-list-cell-db" @change="bindPickerChange" :value="AccessID"
						 :range="AccessGroup" range-key='label'>
							<view class="uni-input">{{AccessGroup[AccessID]['label']}}</view>
						</picker>
					</u-form-item>
					<u-form-item　left-icon='map' :border-bottom='false' label="访问地址" :label-width="170">
						<u-input v-model="form.Address" />
					</u-form-item>
				</u-form>
			</view>
			<!-- 底部按钮 -->
			<view class="foot_vis">
				<view style="width: 40%;display: inline-block;margin: 20rpx 5%;background-color: #FFFFFF;">
					<u-button type="primary" @click="AddVis">
						<u-icon name="plus-circle" color="#fff" size="28"></u-icon>
						添加访客
					</u-button>
				</view>
				<view style="width: 40%;display: inline-block;margin: 20rpx 5%;background-color: #FFFFFF;">
					<u-button type="primary" @click="toVisList">
						<u-icon name="list-dot" color="#fff" size="28"></u-icon>
						访客列表
					</u-button>
				</view>
			</view>
		</view>

		<view v-else class="hasCustomer">
			<!-- {{windowHeight}} -->
			<view v-if="!AddCustomer" :style="{'margin-top': (windowHeight/2 - 150) + 'px'}" class="loading">
				<u-loading style=" margin-left: 300rpx;" mode="flower" size="150"></u-loading>
			</view>
			<!-- 添加套账 -->
			<view v-else class="AddCustomer" :style="{'padding-top': (windowHeight/2 - 150) + 'px','text-align': 'center'}">
				<view style="text-align: center;font-size: 50upx;color: #ff5500;font-weight: 600;margin-bottom: 20upx;">
					当前没绑定账套,请添加账套
				</view>
				<u-button type="success" size="medium" @click="AddCustomerFun">添加账套</u-button>
				<view style="height: 50upx;"></view>
				<u-button type="success" size="medium" @click="resfsh">刷新</u-button>
			</view>
		</view>

		<u-modal width="80%" :show-title='false' :show-cancel-button='true' cancel-text='关闭' @confirm='shareImg' confirm-text='分享'
		 v-model="modelShow">
			<image v-if="ShowCoverimage" class='coveimg' :style="{width: driveWidth*.8+'px',height: (driveWidth*.8)*1.4+'px'}"
			 @click="shareImg" mode='aspectFit' :src="ShareQrImage"></image>
		</u-modal>
		<canvas id="qrcode" canvas-id="qrcode" :style="[{ height: width + 'px', width: width + 'px' }]" />
		<canvas id="sharecanvas" :style="{width: driveWidth*.8+'px',height: (driveWidth*.8)*1.4+'px'}" canvas-id="sharecanvas"></canvas>

		<w-compress ref='wCompress' />
	</view>
</template>

<script>
	import http from '../../common/vmeitime-http/index.js';
	// https://ext.dcloud.net.cn/plugin?id=404
	import avatar from "../../components/yq-avatar/yq-avatar.vue";
	import uQRCode from '../../js_sdk/Sansnn-uQRCode/uqrcode.js';
	import img from '../../static/image/write.png'
	import moment from 'moment';

	import WCompress from '../../components/w-compress/w-compress.vue'
	export default {
		components: {
			avatar,
			WCompress
		},
		data() {
			return {
				QrImage: '',
				qrtext: '',
				width: 250,
				driveWidth: 320,
				ShareQrImage: '',
				windowHeight: null,
				hasCustomer: false,
				AddCustomer: false,
				hasImg: false,
				isChangeImg: false,
				url: '../../static/image/write.png',
				Customer: null,
				AccessID: 0,
				form: {
					VisitorName: "", //姓名
					Reason: "公事", //事由
					Remark: "", //备注
					Phone: "", //手机号
					VisitorCardNo: "", //证件号
					AccessID: '0', //权限组ID
					Expiry: moment().add(1, 'hours').format('YYYY-MM-DD HH:mm'), //有效期
					Interviewee: "", //被访人
					Address: "", //访问地址
				},
				ReasonShow: false,
				Reasonlist: [{
						text: '公事'
					},
					{
						text: '快递'
					},
					{
						text: '私事'
					},
					{
						text: '外卖'
					},
					{
						text: '其它'
					}
				],
				pickerShow: false,
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: false
				},
				Accesstext: '',
				Accessshow: false,
				AccessGroup: [{
					value: 0,
					label: '无'
				}],
				modelShow: false,
				ShowCoverimage: false
			}
		},
		created() {
			http.GetCustomerList().then(res => {
				console.log(res);
				if (res.data.customerlist.length) {
					this.Custome = res.data.customerlist[0]
					this.form.Interviewee = this.Custome.PName;

				}
			}).catch(err => {
				console.log(err);
			});
			http.GetAccessGroup().then(res => {
				console.log(res);
				let AccessGroup = res.data ? res.data : [];
				let AccessGrouplist = AccessGroup.map(item => {
					return {
						value: item.AccessID,
						label: item.GroupName
					}
				})
				this.AccessGroup = [...[{
					value: 0,
					label: '无'
				}], ...AccessGrouplist]
			}).catch(err => {
				console.log(err);
			})
		},
		onShow() {
			console.log(3)
			this.getData();
		},
		onReady() {
			const {
				windowWidth,
				windowHeight
			} = uni.getSystemInfoSync();
			this.width = windowWidth * 0.75;
			this.windowHeight = windowHeight;
			this.driveWidth = windowWidth;
		},
		methods: {
			resfsh() {
				this.hasCustomer = false
				this.AddCustomer = false
				this.getData()
			},
			getData() {
				http.GetCustomerList().then(res => {
					this.AddCustomer = true;
					if (res.data.customerlist.length) {
						this.hasCustomer = true;
						this.Custome = res.data.customerlist[0]
						this.form.Interviewee = this.Custome.PName;
					} else {
						this.hasCustomer = false;
					}
				}).catch(err => {
					this.AddCustomer = false;
				})
			},
			actionSheetCallback(index) {
				this.form.Reason = this.Reasonlist[index].text;
			},
			myUpload(rsp) {
				// this.url = rsp.path; //更新头像方式一
				// console.log(rsp.path)
				//rsp.avatar.imgSrc = rsp.path; //更新头像方式二
				this.isChangeImg = true;
				uni.showLoading({
					title: '图片压缩中...',
					mask: true
				})
				this.$refs.wCompress.start(rsp.path, {
						pixels: 200000, // 最大分辨率，默认二百万
						quality: 0.1, // 压缩质量，默认0.8
						type: 'png', // 图片类型，默认jpg
						base64: true, // 是否返回base64，默认false，非H5有效
					})
					.then(ress => {
						console.error(ress)
						this.url = ress;
					})
					.catch(e => {
						
					})
				// const imgData = uni.getFileSystemManager().readFileSync(rsp.path, 'base64');
				// const base64 = 'data:image/png;base64,' + imgData;
				
				// console.log(base64)
			},
			setTime(val) {
				let time = `${val.year}-${val.month}-${val.day} ${val.hour}:${val.minute}`
				this.form.Expiry = moment(time).format('YYYY-MM-DD HH:mm');
			},
			AccessClick(e) {
				console.log(e);
				this.Accesstext = e[0].label;
				this.form.AccessID = e[0].value
				http.GetDoorValidType({
					AccessID: this.form.AccessID
				}).then(res => {
					console.log(res);
					if (res.data.sTypeList) {
						if (res.data.sTypeList[0] == 'image') {
							this.hasImg = true;
						}
					} else {
						this.hasImg = false;
					}
				}).catch(err => {
					this.hasImg = false;
				})
			},
			AddVis() {
				let that = this;
				if (this.form.VisitorName === '') {
					uni.showToast({
						title: '请输入访客姓名！',
						icon: 'none'
					})
					return
				}
				// console.log(this.data.Phone != '', this.data.VisitorCardNo != '', !(this.data.Phone != '' || this.data.VisitorCardNo != ''))
				if (!(this.form.Phone != '' || this.form.VisitorCardNo != '')) {
					// Toast('请输入手机号或者证件号');
					uni.showToast({
						title: '请输入手机号或者证件号！',
						icon: 'none'
					})
					return
				}
				let d;
				if (this.form.Phone !== '') {
					if (d = /^[1][3,4,5,7,8][0-9]{9}$/, !1 === d.test(this.form.Phone)) return void uni.showToast({
						title: '请输入正确的手机号！',
						icon: 'none'
					});
				}
				if (this.form.VisitorCardNo !== '') {
					if (d =
						/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
						!1 === d.test(this.form.VisitorCardNo)) return void uni.showToast({
						title: '请输入正确的证件号！',
						icon: 'none'
					});
				}
				if (this.form.Interviewee === '') {
					// Toast('请输入被访公司或人员')
					uni.showToast({
						title: '请输入被访公司或人员！',
						icon: 'none'
					})
					return
				}
				if (this.form.AccessID == 0) {
					uni.showToast({
						title: '请提醒管理员添加访客权限组！',
						icon: 'none'
					})
					return
				}
				if (this.form.AccessID == '') {
					uni.showToast({
						title: '请选择有权限的权限组！',
						icon: 'none'
					})
					return
				}


				let parma = {
					VisitorName: this.form.VisitorName,
					Reason: this.form.Reason,
					Remark: this.form.Remark,
					Phone: this.form.Phone,
					VisitorCardNo: this.form.VisitorCardNo,
					AccessID: this.form.AccessID,
					Expiry: this.form.Expiry,
					Interviewee: this.form.Interviewee,
					Address: this.form.Address
				}
				if (this.hasImg) {
					if (this.isChangeImg) {
						parma.base64 = this.url;
					} else {
						uni.showToast({
							title: '此权限需要上传图片！',
							icon: 'none'
						})
						return
					}
				} else {
					uni.showToast({
						title: '此权限需要上传图片！',
						icon: 'none'
					})
					return
				}
				http.AddVisitor(parma).then(res => {
					console.log(res.data);
					if (res.data.result) {
						uni.showToast({
							title: '添加成功',
							icon: 'none'
						})
						that.qrtext = res.data.CardData;
						console.error(123);
						that.make()
						that.hasImg = false;
						that.isChangeImg = false;
						that.url = '../../static/image/write.png';

						that.Accesstext = '';
						that.form = {
							VisitorName: "", //姓名
							Reason: "公事", //事由
							Remark: "", //备注
							Phone: "", //手机号
							VisitorCardNo: "", //证件号
							AccessID: '', //权限组ID
							Expiry: moment().add(1, 'days').format('YYYY-MM-DD HH:mm'), //有效期
							Interviewee: "", //被访人
							Address: "", //访问地址
						}
					} else {
						uni.showToast({
							title: '添加失败，' + res.data,
							icon: 'none'
						})
					}
				}).catch(err => {
					console.error(err);
				})
			},
			//
			toVisList() {
				console.log(123);
				uni.navigateTo({
					url: '../VisitorList/VisitorList'
				})
			},
			//
			AddCustomerFun() {
				uni.navigateTo({
					url: '../AddPerson/AddPerson'
				});
			},
			bindPickerChange(e) {
				console.log(e.target.value);
				this.AccessID = e.target.value
				this.form.AccessID = this.AccessGroup[e.target.value]['value'];
				http.GetDoorValidType({
					AccessID: this.form.AccessID
				}).then(res => {
					console.log(res);
					if (res.data.sTypeList) {
						if (res.data.sTypeList[0] == 'image') {
							this.hasImg = true;
						}
					} else {
						this.hasImg = false;
					}
				}).catch(err => {
					this.hasImg = false;
				})
			},
			//
			shareImg() {
				let that = this;
				uni.previewImage({
					urls: [that.ShareQrImg],
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			//
			canvasDraw() {
				// var context = 
				this.ShowCoverimage = false;
				let ctx = uni.createCanvasContext('sharecanvas');
				let that = this;
				// uni.downloadFile({
				// url: that.QrImage,
				// success: function(res) {
				console.log('获得图片')
				ctx.save()
				ctx.beginPath()

				let canvaswidths = that.driveWidth * .8;
				let qrwidth = canvaswidths - 80; //二维码宽度
				// ctx.drawImage(res.path, 0, 60, that.data.canvasWidth, 400)
				ctx.width = canvaswidths;
				ctx.height = canvaswidths * 1.4;
				ctx.clearRect(0, 10, canvaswidths, canvaswidths * 1.4);
				ctx.fillStyle = "#fff";
				ctx.fillRect(0, 20, canvaswidths, canvaswidths * 1.4);
				ctx.drawImage(that.QrImage, (canvaswidths - qrwidth) / 2, 60, qrwidth, qrwidth) //二维码
				ctx.setTextAlign('center') // 文字居中
				ctx.setFillStyle('#000000') // 文字颜色：黑色
				ctx.setFontSize(15) // 文字字号：22px
				ctx.fillText('二维码有效期：' + moment(that.form.Expiry).format('YYYY-MM-DD HH:mm:ss'), canvaswidths / 2,
					canvaswidths * 1.1)
				ctx.fillText('点击图片长按分享', canvaswidths / 2, canvaswidths * 1.2 + 20)
				ctx.fillText('访客二维码', canvaswidths / 2, 60)
				ctx.stroke()
				ctx.draw()
				setTimeout(function() {
					uni.canvasToTempFilePath({
						canvasId: 'sharecanvas',
						success: function(res) {
							console.error(res)

							var tempFilePath = res.tempFilePath;
							console.log(tempFilePath);
							that.ShareQrImg = tempFilePath;
							const imgData = uni.getFileSystemManager().readFileSync(tempFilePath, 'base64');
							const base64 = 'data:image/png;base64,' + imgData;
							console.log(base64)
							that.ShareQrImage = base64;
							that.modelShow = true;
							uni.hideToast();
							that.ShowCoverimage = true;
						},
						fail: function(res) {
							uni.hideToast();
							console.error(res);
						},
						complete: (res) => {
							uni.hideToast();
							console.error(res)
						}
					})
				}, 1000)
			},
			//
			make() {
				let that = this;
				uQRCode.make({
					canvasId: 'qrcode',
					componentInstance: this,
					text: this.qrtext ? this.qrtext : 'fcard',
					size: this.width,
					margin: 10,
					backgroundColor: '#ffffff',
					foregroundColor: '#000000',
					fileType: 'jpg',
					correctLevel: uQRCode.defaults.correctLevel,
					success: res => {
						console.error(res);
						that.QrImage = res;
						that.canvasDraw()
					}
				});
			},

		}
	}
</script>

<style lang="scss">
	.Visitor {
		width: 100%;
		height: 100%;
		overflow: hidden;
		overflow-y: auto;
		position: relative;

		#qrcode {
			position: absolute;
			left: -100%;
			width: 100%;
			height: 100%;
			top: 0;
		}

		#sharecanvas {
			position: absolute;
			left: 100%;
			width: 100%;
			height: 100%;
			top: 0;
		}

		.imgBox {
			margin-left: 250upx;
			margin-top: 30upx;
			position: relative;
			width: 250upx;
			height: 333.33upx;
		}

		.clr-wrapper {
			text-align: center !important;

			>.my-slider {
				display: none !important;
			}
		}

		.Form_vis {
			width: 700upx;
			margin: 20upx 0;
			padding: 50upx 10upx;
			margin-left: 25upx;
			border-radius: 10upx;
			background-color: #fff;
			box-shadow: 0 2upx 12upx 0 rgba(0, 0, 0, .1);
			box-sizing: border-box;
			transition: box-shadow .5s;
			overflow: hidden;

			.u-form-item {
				padding: 2px 15px;
			}
		}

		.hasCustomer {
			height: 100%;
			overflow-y: auto;
			padding-bottom: 120rpx;
		}

		.foot_vis {
			width: 100%;
			background-color: #fff;
			z-index: 9;
			position: fixed;
			left: 0;
			bottom: 0;
		}
	}
</style>
